using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.GamerServices;
using System.Xml.Serialization;
using System.IO;
using System.IO.IsolatedStorage;

namespace WiMo.Games.GameEngine.WP7S.XNA
{
    /// <summary>
    /// Default implementation of a state manager, all strings are stored in their own file
    /// pretty sure there is a better mechanism for saving key-value pairs, but this is a 
    /// reference implementation.
    /// </summary>
    public class StateManager : IStateManager
    {
        IGameEngine _gameEngine;

        public StateManager(IGameEngine engine)
        {
            _gameEngine = engine;
        }

        public void Store(string key, string value)
        {
            var storage = IsolatedStorageFile.GetUserStoreForApplication();
            using (var file = storage.CreateFile(string.Format("{0}.txt", key)))
            {
                using (var writer = new StreamWriter(file))
                {
                    writer.Write(value);
                }
            }
        }

        public string Get(string key, string defaultValue)
        {
            var storage = IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                using (var file = storage.OpenFile(string.Format("{0}.txt", key), FileMode.Open, FileAccess.Read))
                {
                    using (var reader = new StreamReader(file))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (IsolatedStorageException)
            {
                return defaultValue;
            }
            catch (FileNotFoundException)
            {
                return defaultValue;
            }
        }

        public void ClearAll()
        {
            throw new NotImplementedException();
        }
    }
}